Boomy DDS SDK Development Guide V
I. About
This document guides readers to write audio control code with MediaController for robot external audio stream playback. It supports starting, pausing, resuming and stopping music playback, as well as volume adjustment during playback, to implement a simple robot music player and reproduce the corresponding audio demo effects.
This document has four sections : Section 2 Preparations. Section 3 introduces code cloning, code explanation, deployment path and compilation steps to implement robot external audio stream playback, supporting play, pause, resume, stop and runtime volume adjustment for a simple robot music player. Section 4 Final effect verification and presentation.
Automation Function Objectives: Implement robot external audio stream playback via MediaController. It supports play, pause, resume, stop and runtime volume adjustment to build a simple robot music player. Developers do not need to redesign the robot’s audio control logic. Instead, they can invoke existing SDK audio interfaces and combine them to form a complete action workflow.
II. Prerequisites
Environment Specifications
Operating System: Ubuntu 22.04
Note: ROS environment is not required for SDK compilation
Supported Architectures: x86_64 / ARM
(I) Connect to the Robot
1.Wired Connection
-
Prepare a standard household RJ45 Ethernet cable.
-
Set the IP address of your PC’s wired network interface to 192.168.55.100 (values from 103 to 110 are also acceptable) , and the subnet mask to 255.255.255.0.
-
With this configuration, connect your PC directly to the Boomy robot via the Ethernet cable. Run the
ping 192.168.55.102command. A successful ping indicates that the communication link works properly.

- Connect to the robot computing board via SSH service
ssh noetix@192.168.55.101 #Connect to the compute board, Password: Boomy
2.Wireless Connection
- Obtain the wireless IP: Check the robot Wi‑Fi IP from the Wi‑Fi connection status on the mobile App. (The compute board uses the motion control board’s Wi‑Fi module.)

- Run the connection command: Connect using the command with port parameters.
ssh -p 2222 noetix@[Robot WIFI-IP]
(II) SDK Source Code Acquisition, Build and Compilation
1.Obtain the SDK Source Code
Official URL: GitHub - Noetix-Robotics/noetix_sdk_boomy: This is SDK for Noetix robot Boomy with DDS interface.
III. Start
(I) Clone the SDK
git clone git@github.com:Noetix-Robotics/noetix_sdk_boomy.git
cd noetix_sdk_boomy
(II) Start of C++ Code
1.Create src folder and out folder
mkdir src
mkdir out
2.Write the main.cpp file under the src folder
vim src/main.cpp
#include "MediaController.h"
#include <unistd.h>
#include <cstdlib>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <thread>
#include <atomic>
#include <vector>
#include <cstdio>
using namespace noetix;
// Music stop flag
static std::atomic<bool> music_stop(false);
// Music pause flag. The sending thread must stop sending on pause to prevent data accumulation or loss at the device.
static std::atomic<bool> music_pause(false);
// Playback thread alive flag. Do not rely on joinable () to check playback state, as a terminated std::thread is still joinable.
static std::atomic<bool> music_playing(false);
// ==================== Read WAV file ====================
// Parse WAV file, return raw PCM samples with channel count and sample rate.
// Traverse standard RIFF chunks, support WAV with extended headers and additional chunks.
static bool load_wav(const std::string &path, std::vector<int16_t> &pcm,
uint32_t &channels, uint32_t &sample_rate) {
std::ifstream f(path, std::ios::binary);
if (!f.is_open()) {
printf("[ERROR] cannot open %s\n", path.c_str());
return false;
}
// Read RIFF header
char tag[4];
f.read(tag, 4);
if (memcmp(tag, "RIFF", 4) != 0) {
printf("[ERROR] not a WAV file\n");
return false;
}
f.ignore(4); // file size
f.read(tag, 4);
if (memcmp(tag, "WAVE", 4) != 0) {
printf("[ERROR] not a WAV file\n");
return false;
}
uint32_t data_bytes = 0;
bool found_fmt = false, found_data = false;
while (f.good() && !found_data) {
f.read(tag, 4);
uint32_t chunk_size;
f.read(reinterpret_cast<char *>(&chunk_size), 4);
if (memcmp(tag, "fmt ", 4) == 0) {
uint16_t audio_format, ch, bits;
uint32_t sr;
f.read(reinterpret_cast<char *>(&audio_format), 2);
f.read(reinterpret_cast<char *>(&ch), 2);
f.read(reinterpret_cast<char *>(&sr), 4);
f.ignore(4); // byte_rate
f.ignore(2); // block_align
f.read(reinterpret_cast<char *>(&bits), 2);
if (chunk_size > 16)
f.ignore(chunk_size - 16);
if (audio_format != 1) {
printf("[ERROR] unsupported format %u (need PCM)\n",
audio_format);
return false;
}
if (bits != 16) {
printf("[ERROR] only 16-bit PCM supported\n");
return false;
}
channels = ch;
sample_rate = sr;
found_fmt = true;
} else if (memcmp(tag, "data", 4) == 0) {
data_bytes = chunk_size;
found_data = true;
} else {
f.ignore(chunk_size);
}
}
if (!found_fmt || !found_data) {
printf("[ERROR] invalid WAV file\n");
return false;
}
size_t num_samples = data_bytes / sizeof(int16_t);
pcm.resize(num_samples);
f.read(reinterpret_cast<char *>(pcm.data()), data_bytes);
return true;
}
// Convert to 2ch interleaved for device speaker playback.
// - 1ch: Copy samples to both left and right channels.
// - 2ch: Return samples as-is.
// - >2 Channels: Select first 2 channels.
static void convert_to_2ch_interleaved(const std::vector<int16_t> &in,
uint32_t in_channels,
std::vector<int16_t> &out) {
if (in_channels == 2) {
out = in;
return;
}
size_t frames = in.size() / in_channels;
out.resize(frames * 2);
if (in_channels == 1) {
for (size_t i = 0; i < frames; i++) {
out[i * 2] = in[i];
out[i * 2 + 1] = in[i];
}
return;
}
for (size_t i = 0; i < frames; i++) {
out[i * 2] = in[i * in_channels];
out[i * 2 + 1] = in[i * in_channels + 1];
}
}
// ==================== Implement playback ====================
// Subscribe to device local playback stream for original sample rate detection (1s timeout). Use 16000 as fallback value when undetected.
// Device firmware consumes audio streams at a fixed sample rate and ignores the stream.sample_rate field.
// Resample to target rate before transmission to prevent speed and pitch shift.
static uint32_t detect_playback_sample_rate(MediaController *ctrl) {
static std::atomic<uint32_t> detected{0};
detected = 0;
ctrl->subscribe_internal_audio_playback(
[](const media::AudioStream &stream) {
uint32_t expect = 0;
detected.compare_exchange_strong(expect,
stream.sample_rate);
});
sleep_ms(1000);
uint32_t sr = detected.load();
return sr ? sr : 16000;
}
// 2ch interleaved PCM linear resampling; process left and right channels independently to prevent crosstalk.
static void resample_2ch_interleaved(const std::vector<int16_t> &in,
uint32_t in_rate, uint32_t out_rate,
std::vector<int16_t> &out) {
if (in_rate == out_rate || in.size() < 2) {
out = in;
return;
}
size_t frames = in.size() / 2;
size_t out_frames = (size_t)((double)frames * out_rate / in_rate);
out.resize(out_frames * 2);
double scale = (double)(frames - 1) / (double)(out_frames - 1);
for (size_t i = 0; i < out_frames; i++) {
double pos = i * scale;
size_t idx = (size_t)pos;
double frac = pos - idx;
size_t nxt = idx + 1 < frames ? idx + 1 : idx;
out[i * 2] = (int16_t)((1.0 - frac) * in[idx * 2] +
frac * in[nxt * 2]);
out[i * 2 + 1] = (int16_t)((1.0 - frac) * in[idx * 2 + 1] +
frac * in[nxt * 2 + 1]);
}
}
// Demonstrate audio playback via publish_external_audio_playback_stream.
// (2ch interleaved, 20ms frame slicing)
static void cmd_external_audio_playback(MediaController *ctrl,
const std::string &wav_path) {
printf("[CMD] external_audio_playback: %s\n", wav_path.c_str());
music_playing = true;
std::vector<int16_t> pcm;
uint32_t channels = 0, sample_rate = 0;
if (!load_wav(wav_path, pcm, channels, sample_rate))
return;
printf("[INFO] loaded: %zu samples, %u ch, %u Hz\n", pcm.size(),
channels, sample_rate);
// convert to 2-channel interleaved
std::vector<int16_t> pcm_2ch;
convert_to_2ch_interleaved(pcm, channels, pcm_2ch);
printf("[INFO] converted to 2ch: %zu samples\n", pcm_2ch.size());
// Resample to the device’s native sample rate (otherwise playback speed and pitch will shift).
uint32_t target_sr = detect_playback_sample_rate(ctrl);
printf("[INFO] target sample rate: %u Hz\n", target_sr);
if (target_sr != sample_rate) {
std::vector<int16_t> resampled;
resample_2ch_interleaved(pcm_2ch, sample_rate, target_sr,
resampled);
pcm_2ch = std::move(resampled);
sample_rate = target_sr;
printf("[INFO] resampled: %zu samples\n", pcm_2ch.size());
}
uint32_t frame_samples = sample_rate / 50 * 2; // 20ms, 2ch
if (frame_samples == 0)
frame_samples = 2;
size_t offset = 0;
// Absolute time base: The offset frame (2ch interleaved samples)
// is scheduled at start_time + offset / 2 /sample_rate.
// Eliminates cumulative drift from publish overhead, unlike fixed 20ms sleep per frame,
// Suppress noise from device buffer underrun.
auto start_time = std::chrono::steady_clock::now();
while (offset < pcm_2ch.size()) {
if (music_stop.load())
break;
// Stop sending when paused to avoid data accumulation/loss and resulting noise or skipping.
if (music_pause.load()) {
sleep_ms(20);
// Reset time base upon resume to avoid instant burst backfill.
start_time = std::chrono::steady_clock::now() -
std::chrono::microseconds((int64_t)(
(double)offset / 2 * 1000000.0 /
sample_rate));
continue;
}
// Align sending pace to absolute timeline.
auto target = start_time + std::chrono::microseconds((int64_t)(
(double)offset / 2 * 1000000.0 /
sample_rate));
auto now = std::chrono::steady_clock::now();
if (target > now)
std::this_thread::sleep_until(target);
// Catch up directly when lagging behind timeline without additional sleep.
size_t chunk =
std::min((size_t)frame_samples, pcm_2ch.size() - offset);
media::AudioStream stream;
stream.timestamp_us = get_time_us();
stream.channels = 2;
stream.sample_rate = sample_rate;
stream.format = 2; // 16-bit LE
stream.duration_ms = chunk / 2 * 1000 / sample_rate;
stream.audio_data.assign(pcm_2ch.begin() + offset,
pcm_2ch.begin() + offset + chunk);
ctrl->publish_external_audio_playback_stream(stream);
offset += chunk;
}
printf("[CMD] external_audio_playback done\n");
music_playing = false;
}
// ==================== Send control commands ====================
// Pause playback
static void cmd_music_pause(MediaController *ctrl)
{
// 1. Stop the feeding thread first.
music_pause = true;
// 2. Wait until the last frame is sent, then pause device playback.
sleep_ms(30);
ctrl->pause_audio_playback();
printf("[INFO] Music paused\n");
}
// Resume playback
static void cmd_music_resume(MediaController *ctrl)
{
// 1. Resume device playback first.
ctrl->resume_audio_playback();
sleep_ms(30);
// 2. Then resume frame feeding in the sending thread (the thread resets the time base internally).
music_pause = false;
printf("[INFO] Music resumed\n");
}
// Increase volume
static void cmd_volume_up(MediaController *ctrl)
{
int volume = ctrl->get_volume() + 10;
if (volume > 200)
volume = 200;
ctrl->set_volume(volume);
printf("[INFO] Current volume: %d\n", ctrl->get_volume());
}
// Decrease volume
static void cmd_volume_down(MediaController *ctrl)
{
int volume = ctrl->get_volume() - 10;
if (volume < 0)
volume = 0;
ctrl->set_volume(volume);
printf("[INFO] Current volume: %d\n", ctrl->get_volume());
}
// ==================== Music player ====================
static void cmd_music_party(MediaController *ctrl)
{
printf("\n========== Music Party ==========\n");
// 1. Set initial volume.
ctrl->set_volume(160);
// 2. Enable external audio stream output to the internal speaker.
ctrl->set_external_custom_audio_data_to_playback_enable(true);
printf("[INFO] Current volume: %d\n", ctrl->get_volume());
music_stop = false;
// 3. Create playback thread.
std::thread music_thread;
// 4. Wait for user input control commands.
printf("\n========== Music Control ==========\n");
printf("s - Start music\n");
printf("p - Pause music\n");
printf("r - Resume music\n");
printf("+ - Volume up\n");
printf("- - Volume down\n");
printf("q - Stop music and exit\n");
printf("===================================\n");
std::string input;
while (true)
{
printf("Command> ");
if (!std::getline(std::cin, input))
{
music_stop = true;
break;
}
if (input == "s")
{
if (music_playing.load())
{
printf("[WARN] Music has already started\n");
continue;
}
// Recycle terminated old thread
if (music_thread.joinable())
music_thread.join();
music_stop = false;
music_pause = false;
music_thread = std::thread(cmd_external_audio_playback, ctrl,
std::string("./out/music.wav"));
printf("[INFO] Music started\n");
}
else if (input == "p")
{
if (music_playing.load())
cmd_music_pause(ctrl);
else
printf("[WARN] Please start music first\n");
}
else if (input == "r")
{
if (music_playing.load())
cmd_music_resume(ctrl);
else
printf("[WARN] Please start music first\n");
}
else if (input == "+")
{
cmd_volume_up(ctrl);
}
else if (input == "-")
{
cmd_volume_down(ctrl);
}
else if (input == "q")
{
music_stop = true;
printf("[INFO] Stopping music...\n");
break;
}
else
{
printf("[WARN] Unknown command\n");
}
}
// 5. Wait for playback thread to exit
if (music_thread.joinable())
{
music_thread.join();
}
// 6. Stop external audio playback
ctrl->set_external_custom_audio_data_to_playback_enable(false);
printf("[INFO] Music party finished\n");
}
int main(int argc, char *argv[])
{
// ========== 1. Configure DDS environment ==========
char buf[256];
getcwd(buf, sizeof(buf));
std::string path = std::string(buf);
std::string ddsxml = "file://" + path + "/config/dds.xml";
setenv("CYCLONEDDS_URI", ddsxml.c_str(), 1);
printf("cur path is %s\n", path.c_str());
// ========== 2. Get MediaController singleton and initialize it ==========
MediaController *ctrl = MediaController::Instance();
ctrl->init();
// ========== 3. Wait for DDS data synchronization ==========
sleep_ms(1000);
// ========== 4. Run the music player ==========
cmd_music_party(ctrl);
return 0;
}
Modify this line to use your own audio file.
//The audio file used in the current code is:./out/music.wav
music_thread = std::thread(cmd_external_audio_playback, ctrl,
std::string("./out/music.wav"));
All audio-related APIs in the code communicate with the motion control board’s voice module via DDS Topics to establish a communication link. They support control of Boomy audio peripherals (speakers, microphones, etc.), as well as voice agent configuration and data stream management. The specific interfaces are listed below:
| MediaController Interface | ||
|---|---|---|
| Interface Name | Interface Description | return type |
| Instance | Obtain the singleton pointer of MediaController | Object pointer |
| init | MediaController Object Initialization | bool |
| set_system_control | Set the control status of the voice interaction system | None |
| subscribe_system_status | Subscribe to status information of the audio-visual interactive system | None |
| subscribe_system_error | Subscribe to error status information of audio-visual interaction system | None |
| get_volume | Get the current volume of the audio-visual interaction system Range: 0–200 | int |
| set_volume | Set the volume of the current audio-visual interaction system Range: 0–200 | None |
| get_timeout | Get the inactivity timeout before entering sleep mode | int |
| set_timeout | Set the inactivity timeout before entering sleep mode | None |
| get_audio_cue_enable | get the enabled status of the prompt tone of the audio-visual interaction system | bool |
| set_audio_cue_enable | Set whether the prompt sound of the audio-visual interaction system is enabled | None |
| get_internal_capture_audio_data_to_agent_enable | Get the internal microphone audio input status for the Agent | bool |
| set_internal_capture_audio_data_to_agent_enable | Set the internal microphone audio input status for the Agent | None |
| get_external_custom_audio_data_to_agent_enable | Get the enabled status of external audio stream input for the agent | bool |
| set_external_custom_audio_data_to_agent_enable | Get the enabled status of external audio stream input for the agent | None |
| get_internal_agent_audio_data_to_playback_enable | Get the enabled status of agent audio stream output to the internal speaker. | bool |
| set_internal_agent_audio_data_to_playback_enable | Set the enabled status of agent audio stream output to the internal speaker. | None |
| get_external_custom_audio_data_to_playback_enable | Get the enabled status of external audio stream output to the internal speaker. | bool |
| set_external_custom_audio_data_to_playback_enable | Get the enabled status of external audio stream output to the internal speaker. | None |
| get_internal_capture_video_data_to_agent_enable | Get the enabled status of internal video stream input to the agent. | bool |
| set_internal_capture_video_data_to_agent_enable | Set the enabled status of internal video stream input to the agent. | None |
| get_external_custom_video_data_to_agent_enable | Get the enabled status of external video stream input to the agent. | bool |
| set_external_custom_video_data_to_agent_enable | Set the enabled status of external video stream input to the agent. | None |
| get_external_custom_audio_data_to_agent_use_internal_3a | Get the enabled status of using the internal 3A algorithm for external audio stream input to the agent. | bool |
| set_external_custom_audio_data_to_agent_use_internal_3a | Set the enabled status of using the internal 3A algorithm for external audio stream input to the agent. | None |
| get_wakeup_response_words | Get wake-up response words | string |
| set_wakeup_response_words | Set wake-up response words | None |
| get_sleep_response_words | Get dormant response words | string |
| set_sleep_response_words | Set sleep response words | None |
| get_wakeup_words | Get all wake words | string |
| add_wakeup_words | Add wake-up words | bool |
| reset_wakeup_words | Reset factory default wake-up word | None |
| subscribe_internal_audio_capture | Subscribe to the audio stream captured by the internal microphone | None |
| subscribe_internal_audio_playback | Subscribe to the audio stream played by the robot's internal speaker | None |
| subscribe_internal_video_capture | Subscribe to the video stream collected by the camera inside the robot (only available for Boomy without computing power board) | VideoStream struct |
| subscribe_internal_video_desensed | Subscribe to the audio-visual interaction system. The processed desensitized video stream (the Boomy equipped with a computing power board needs to continuously publish the availability of the external video stream) | VideoStream struct |
| pause_video_capture | Pause the internal camera Data Acquisition of the robot (only available for Boomy without computing power board) | None |
| resume_video_capture | Resume the internal camera Data Acquisition of the robot (only available for Boomy without computing power board) | None |
| publish_external_video_stream | Publish external video streams to the audio-visual interaction system | None |
| publish_external_audio_stream | Publish external audio stream input to the agent | None |
| publish_external_audio_playback_stream | Publish external audio stream output to the internal speaker | None |
| pause_audio_capture | Pause internal microphone audio stream capture | None |
| resume_audio_capture | Resume internal microphone audio stream capture | None |
| pause_audio_playback | Pause the audio stream output of the internal speaker | None |
| resume_audio_playback | Resume the audio stream output of the internal speaker | None |
Supported audio stream parameters: channels=8, sample_rate=16000, format=2 (16-bit little-endian) only.

Audio Stream Data Structure
| Audio Stream Structure | Function Prototype | Example Value | Description |
|---|---|---|---|
| AudioStream | | header | DDS Packet Header |
| timestamp_us | Timestamp (us) | ||
| channels | Channel Count | ||
| sample_rate | Sample Rate | ||
| format | Data Format | ||
| duration_ms | Time (ms) | ||
| audio_data | Audio Data |
For more details, refer to: Boomy Comprehensive Usage Document
3.Modify CMakeLists.txt Build File
Modify the content of the CMakeLists.txt file under this path:
- Add Example
Locate add_executable(example_media examples/cpp/example_media.cpp) in the file, and append the newly written code right below this line.
add_executable(main src/main.cpp)
add_executable is a CMake command, which is used to define an executable target.
- Set Path
Similarly, locate target_include_directories in the file and add content below this line.
target_include_directories sets header search paths for the target example_standswing.
target_include_directories(main
PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
- Specify Linking
Similarly, locate target_link_libraries in the file and add content below this line.
target_link_libraries is used to specify libraries to link for the given target.It tells the linker to combine symbols and functions from these libraries into the final executable.
target_link_libraries(main
Threads::Threads
noetix_boomy_sdk
${DDS_LIB_DIR}/libddsc.so
${DDS_LIB_DIR}/libddscxx.so
)
- Full CMakeLists.txt File
4.Compile the Code
Save and exit, then run the build script in the project root directory.
./build.sh
As shown below:

5.Run the Code
sudo ./build/main
(III) Python Start
1.Create main.py Python File
Write main.py under the src folder.
vim src/main.py
2.Write Python Code
import os
import sys
import threading
import wave
from array import array
from time import perf_counter, sleep, time
# DDS environment configuration (parse project root directory based on script path, independent of working directory at runtime)
PROJECT_ROOT = os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
)
os.environ["CYCLONEDDS_URI"] = "file://" + os.path.join(PROJECT_ROOT, "config", "dds.xml")
sys.path.append(os.path.join(PROJECT_ROOT, "build"))
# Default music file path (out/music.wav under project root directory)
WAV_PATH = os.path.join(PROJECT_ROOT, "out", "music.wav")
from mediacontrol_py import AudioStream, MediaController
# Music stop flag (C++ std::atomic<bool> music_stop)
music_stop = threading.Event()
# Music pause flag (sender thread shall stop transmission on pause; otherwise data accumulation or loss occurs on device side)
music_pause = threading.Event()
# ========== WAV Read ==========
def load_wav(path):
"""Read 16-bit PCM WAV with standard wave module, returns (int16 list, channels, sample rate)."""
with wave.open(path, "rb") as wf:
channels = wf.getnchannels()
sample_rate = wf.getframerate()
sampwidth = wf.getsampwidth()
raw = wf.readframes(wf.getnframes())
if sampwidth != 2:
raise ValueError(f"only 16-bit PCM supported, got {sampwidth * 8}-bit")
pcm = array("h")
pcm.frombytes(raw)
return pcm.tolist(), channels, sample_rate
def detect_playback_sample_rate(ctrl, wait=1.0):
"""Subscribe to device playback stream for sample rate detection, default 16000 on detection failure.
Firmware uses fixed sample rate and ignores stream.sample_rate.
Resample audio beforehand to avoid pitch/speed distortion.
"""
detected = [0]
def on_playback(stream):
if detected[0] == 0 and stream.sample_rate:
detected[0] = stream.sample_rate
try:
ctrl.subscribe_internal_audio_playback(on_playback)
except Exception as e:
print(f"[WARN] cannot detect playback rate: {e}")
sleep(wait)
return detected[0] or 16000
def resample_2ch_interleaved(pcm_2ch, in_rate, out_rate):
"""2ch interleaved PCM linear resample, per-channel processing to prevent stereo crosstalk."""
if in_rate == out_rate or len(pcm_2ch) < 2:
return pcm_2ch
frames = len(pcm_2ch) // 2
left = pcm_2ch[0::2]
right = pcm_2ch[1::2]
out_frames = int(frames * out_rate / in_rate)
out = [0] * (out_frames * 2)
scale = (frames - 1) / max(out_frames - 1, 1)
for i in range(out_frames):
pos = i * scale
idx = int(pos)
frac = pos - idx
nxt = idx + 1 if idx + 1 < frames else idx
out[i * 2] = int(left[idx] * (1 - frac) + left[nxt] * frac)
out[i * 2 + 1] = int(right[idx] * (1 - frac) + right[nxt] * frac)
return out
def convert_to_2ch_interleaved(pcm, in_channels):
"""Convert to 2ch interleaved PCM, follow example_media implementation.
- 1ch: copy to L/R
- 2ch: pass through
- >2ch: extract first 2 channels
"""
if in_channels == 2:
return pcm
if in_channels == 1:
frames = len(pcm)
out = [0] * (frames * 2)
for i in range(frames):
out[i * 2] = pcm[i]
out[i * 2 + 1] = pcm[i]
return out
frames = len(pcm) // in_channels
out = [0] * (frames * 2)
for i in range(frames):
out[i * 2] = pcm[i * in_channels]
out[i * 2 + 1] = pcm[i * in_channels + 1]
return out
# ========== Playback implementation ==========
def cmd_external_audio_playback(ctrl, wav_path=WAV_PATH):
"""Demonstrates audio playback via publish_external_audio_playback_stream."""
print(f"[CMD] external_audio_playback: {wav_path}")
if not os.path.isfile(wav_path):
print(f"[ERROR] music file not found: {wav_path}")
print("[HINT] Please confirm that out/music.wav exists under the project root directory.")
return
try:
pcm, channels, sample_rate = load_wav(wav_path)
except (wave.Error, ValueError) as e:
print(f"[ERROR] invalid WAV file: {e}")
return
print(f"[INFO] loaded: {len(pcm)} samples, {channels}ch, {sample_rate}Hz")
# convert to 2-channel interleaved(Same as example_media implementation)
pcm_2ch = convert_to_2ch_interleaved(pcm, channels)
print(f"[INFO] converted to 2ch: {len(pcm_2ch)} samples")
# Resample to the device’s native sample rate (otherwise playback speed and pitch will be distorted).
target_sr = detect_playback_sample_rate(ctrl)
print(f"[INFO] target sample rate: {target_sr} Hz")
if target_sr != sample_rate:
pcm_2ch = resample_2ch_interleaved(pcm_2ch, sample_rate, target_sr)
sample_rate = target_sr
print(f"[INFO] resampled: {len(pcm_2ch)} samples")
# Send frames of 20ms duration (2-channel interleaved).
frame_samples = sample_rate // 50 * 2
if frame_samples == 0:
frame_samples = 2
offset = 0
# Absolute time base: The offset frame (2ch interleaved samples)
# is scheduled at start_time + offset / 2 /sample_rate.
# Eliminates cumulative drift from publish overhead, unlike fixed 20ms sleep per frame,
# Suppress noise from device buffer underrun.
start_time = perf_counter()
while offset < len(pcm_2ch):
if music_stop.is_set():
break
# Stop sending when paused to avoid data accumulation/loss and resulting noise or skipping.
if (music_pause.load()) {
if music_pause.is_set():
sleep(0.02)
# Reset time base upon resume to avoid instant burst backfill.
start_time = perf_counter() - offset / 2 / sample_rate
continue
# Align sending pace to absolute timeline.
target = start_time + offset / 2 / sample_rate
now = perf_counter()
if target > now:
sleep(target - now)
# Catch up directly when lagging behind timeline without additional sleep.
chunk = pcm_2ch[offset : offset + frame_samples]
stream = AudioStream()
stream.timestamp_us = int(time() * 1e6)
stream.channels = 2
stream.sample_rate = sample_rate
stream.format = 2 # 16-bit LE
stream.duration_ms = len(chunk) // 2 * 1000 // sample_rate
stream.audio_data = chunk
ctrl.publish_external_audio_playback_stream(stream)
offset += frame_samples
print("[CMD] external_audio_playback done")
# ========== Send control commands ==========
def cmd_music_pause(ctrl):
# 1. Stop the feeding thread first.
music_pause.set()
# 2. Wait until the last frame is sent, then pause device playback.
sleep(0.03)
ctrl.pause_audio_playback()
print("[INFO] Music paused")
def cmd_music_resume(ctrl):
# 1. Resume device playback first.
ctrl.resume_audio_playback()
sleep(0.03)
# 2. Then resume frame feeding in the sending thread (the thread resets the time base internally).
music_pause.clear()
print("[INFO] Music resumed")
def cmd_volume_up(ctrl):
volume = min(ctrl.get_volume() + 10, 200)
ctrl.set_volume(volume)
print(f"[INFO] Current volume: {ctrl.get_volume()}")
def cmd_volume_down(ctrl):
volume = max(ctrl.get_volume() - 10, 0)
ctrl.set_volume(volume)
print(f"[INFO] Current volume: {ctrl.get_volume()}")
# ========== Music player ==========
def cmd_music_party(ctrl):
print("\n========== Music Party ==========")
# 1. Set initial volume.
ctrl.set_volume(160)
# 2. Enable external audio stream output to the internal speaker.
ctrl.set_external_custom_audio_data_to_playback_enable(True)
print(f"[INFO] Current volume: {ctrl.get_volume()}")
music_stop.clear()
music_thread = None
# 3. Wait for user input control commands.
print("\n========== Music Control ==========")
print("s - Start music")
print("p - Pause music")
print("r - Resume music")
print("+ - Volume up")
print("- - Volume down")
print("q - Stop music and exit")
print("===================================")
while True:
try:
user_input = input("Command> ")
except EOFError:
music_stop.set()
break
if user_input == "s":
if music_thread is not None and music_thread.is_alive():
print("[WARN] Music has already started")
continue
music_stop.clear()
music_pause.clear()
music_thread = threading.Thread(
target=cmd_external_audio_playback, args=(ctrl, WAV_PATH)
)
music_thread.start()
print("[INFO] Music started")
elif user_input == "p":
if music_thread is not None and music_thread.is_alive():
cmd_music_pause(ctrl)
else:
print("[WARN] Please start music first")
elif user_input == "r":
if music_thread is not None and music_thread.is_alive():
cmd_music_resume(ctrl)
else:
print("[WARN] Please start music first")
elif user_input == "+":
cmd_volume_up(ctrl)
elif user_input == "-":
cmd_volume_down(ctrl)
elif user_input == "q":
music_stop.set()
print("[INFO] Stopping music...")
break
else:
print("[WARN] Unknown command")
# 4. Wait for playback thread to exit.
if music_thread is not None:
music_thread.join()
# 5. Stop external audio playback.
ctrl.set_external_custom_audio_data_to_playback_enable(False)
print("[INFO] Music party finished")
def main():
ctrl = MediaController.instance()
ctrl.init()
try:
cmd_music_party(ctrl)
except KeyboardInterrupt:
music_stop.set()
ctrl.set_external_custom_audio_data_to_playback_enable(False)
print("\n[INFO] interrupted, exited")
return 0
if __name__ == "__main__":
sys.exit(main())
Modify this line to use your own audio file.
# The audio file used in the current code is:./out/music.wav
WAV_PATH = os.path.join(PROJECT_ROOT, "out", "music.wav")
3.Compile the Code
Save and exit, then run the build script in the project root directory. The link files required for Python will be generated.
./build.sh
4.Run the Code
After compilation, run the Python code in the project root directory.
python3 src/main.py
IV. Demonstration
The following is the actual robot running effect.
Google Drive video link:https://drive.google.com/file/d/1arT9zO5BwPfmM8zTtS4O5aPzxV_wwCSh/view?usp=drive_link